﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WCLOnlineExam.Models;

namespace WCLOnlineExam.Controllers
{
    [Authorize]
    public class StudentController : EntityController
    {
        public StudentController(IEntityContextBuilder builder) : base(builder) { }
        //
        // GET: /Student/
       
        public ActionResult UserCenter()
        {
            if (Session["user"] == null)
            {
                return RedirectToRoute(new { controller = "Account", action = "Login" });
            }
            else 
            {
                ViewBag.user = Session["user"];
                return View();
            }

        }

        public ActionResult Setting()
        {
            if (Session["user"] == null)
            {
                return RedirectToRoute(new { controller = "Account", action = "Login" });
            }
            else 
            {
                ViewBag.user = Session["user"];
                return View();
            }
        }

        public ActionResult ChangePassword()
        {
            if (Session["user"] == null)
            {
                return RedirectToRoute(new { controller = "Account", action = "Login" });
            }
            else 
            {
                ViewBag.user = Session["user"];
                return View();
            }
        }

        public ActionResult Analysis()
        {
            if (Session["user"] == null)
            {
                return RedirectToRoute(new { controller = "Account", action = "Login" });
            }
            else 
            {
                ViewBag.user = Session["user"];
                IEntityQueryable<Question> context = EntityBuilder.GetContext<Question>();
                int count = context.Count();
                ViewBag.rightAmount = 0;
                ViewBag.wrongAmount = 0;
                ViewBag.restAmount = count - ViewBag.rightAmount - ViewBag.wrongAmount;
                return View();
            }
        }

        public ActionResult ExamHistory()
        {
            if (Session["user"] == null)
            {
                return RedirectToRoute(new { controller = "Account", action = "Login" });
            }
            else 
            {
                ViewBag.user = Session["user"];
                User user = (User)Session["user"];
                IEntityQueryable<ExamResult> context = EntityBuilder.GetContext<ExamResult>();
                ViewBag.ExamResults = context.Query().Where(c => c.user.UserName == user.UserName).ToList();
  
                return View();
            }
        }


        public ActionResult PracticeTest(int id = 0)
        {
            IEntityQueryable<Question> context = EntityBuilder.GetContext<Question>();
            Question[] items = context.OrderBy().Skip(id).Take(1).ToArray();
            int count = context.OrderBy().ToArray().Length;
            ViewBag.count = count;
            if (id < count - 1)
            {
                ViewBag.Next = id + 1;
            }
           
            if (id > 0)
            {
                ViewBag.Previous = id - 1;
            }

            if (items.Length > 0)
            {
                ViewBag.question = items[0];
               
            }
            else
            {
                ViewBag.message = "没有题目了";
            }
            return View();
        }
        public ActionResult ExamList()
        {
            if (Session["user"] == null)
            {
                Response.StatusCode = 400;
                return RedirectToAction("Index", "Error");
            }
            User user = ((User)Session["user"]);
            IEntityQueryable<Exam> context = EntityBuilder.GetContext<Exam>();
            Exam[] exams = context.Query().Where(c => c.UserGroup.FirstOrDefault(e => e.Name == user.Group.Name) != null).ToArray();
            ICollection<StudentExam> StudentExams = new List<StudentExam>();

            IEntityQueryable<ExamResult> ExamResultContext = EntityBuilder.GetContext<ExamResult>();
            ExamResult[] ExamResult = ExamResultContext.Query().Where(c => c.user.UserName == user.UserName).ToArray();

            for (int i = 0; i < exams.Length; i++ )
            {
                StudentExam StudentExam = new StudentExam();
                StudentExam.Exam = exams[i];
                for (int j = 0; j < ExamResult.Length; j++)
                {
                    if (ExamResult[j].exam.Index == exams[i].Index) 
                    {
                        StudentExam.ExamResult = ExamResult[j];
                    }
                }
                StudentExams.Add(StudentExam);
            }

            ViewBag.StudentExams = StudentExams.ToArray();
            return View();
        }
        public ActionResult AnswerExam(Guid id)
        {
            if (Session["user"] == null)
            {
                Response.StatusCode = 400;
                return RedirectToAction("Index", "Error");
            }

            string username = ((User)Session["user"]).UserName;
            var usercontext = EntityBuilder.GetContext<User>();
            User user = usercontext.Query().SingleOrDefault(c => c.UserName == username);

            IEntityQueryable<Exam> context = EntityBuilder.GetContext<Exam>();
            Exam exam = context.Query().SingleOrDefault(c => c.Index == id);
            

            IEntityQueryable<ExamResult> ExamResultContext = EntityBuilder.GetContext<ExamResult>();

            ExamResult result = ExamResultContext.Query().SingleOrDefault(c => c.user.UserName == user.UserName && c.exam.Index == exam.Index);

            if (result != null)
            {
                return RedirectToAction("ExamHistory");
            }

            ViewBag.Exam = exam;
            ViewBag.ExamId = id.ToString();
            return View();
        }

        [HttpPost]
        public ActionResult AnswerExam(string id, List<String> answer)
        {
            if (Session["user"] == null)
            {
                Response.StatusCode = 400;
                return Content("请登录后在做题");
            }
            string username = ((User)Session["user"]).UserName;
            var usercontext = EntityBuilder.GetContext<User>();
            User user = usercontext.Query().SingleOrDefault(c => c.UserName == username);
            IEntityQueryable<Exam> context = EntityBuilder.GetContext<Exam>();
            Exam exam = context.Query().Where(c => c.Index.ToString() == id).First();
            int i = 0;
            int right = 0;

            foreach (Question question in exam.Question)
            {
                if (question.Answer.ToString() == answer[i++])
                {
                    right++;
                }
            }
            IEntityQueryable<ExamResult> ExamResultContext = EntityBuilder.GetContext<ExamResult>();
            ExamResult result= new ExamResult();

            try
            {
                result.Score = right * exam.TotalPoint / exam.Question.Count;
                result.user = user;
                result.exam = exam;
                ExamResultContext.Add(result);
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                return Content("提交失败，请稍后重试");
            }
            
            Response.StatusCode = 200;
            return Content(result.Score + "");
        }
	}
}